import time
import psutil
import threading
import subprocess
import re

class SystemMonitor:
    def __init__(self):
        self.cpu_readings = []
        self.mem_readings = []
        self.is_monitoring = False
        self.monitor_thread = None

    def _get_usage(self):
        """获取当前系统资源使用情况"""
        mem = psutil.virtual_memory()
        return psutil.cpu_percent(interval=1), mem.percent

    def start(self):
        """启动资源监控"""
        self.is_monitoring = True
        self.monitor_thread = threading.Thread(target=self._monitor_loop)
        self.monitor_thread.start()

    def _monitor_loop(self):
        while self.is_monitoring:
            cpu, mem = self._get_usage()
            self.cpu_readings.append(cpu)
            self.mem_readings.append(mem)
            time.sleep(0.5)

    def end(self):
        """结束监控并返回统计数据"""
        self.is_monitoring = False   
        if self.monitor_thread and self.monitor_thread.is_alive():
            try:
                self.monitor_thread.join(timeout=5)  # 增加超时机制
            except RuntimeError:
                pass
        if not self.cpu_readings or not self.mem_readings:
            return (0.0, 0.0)
        return dict(
            avg_cpu = round(sum(self.cpu_readings)/len(self.cpu_readings),2),
            avg_mem = round(sum(self.mem_readings)/len(self.mem_readings),2)
        )


    # 保留原有阻塞式监控方法
    def monitor(self, duration: int):
        self.start()
        time.sleep(duration)
        return self.end()

if __name__ == '__main__':
    monitor = SystemMonitor()
    avg_cpu, avg_mem = monitor.monitor(120)
    print(f'平均CPU使用率: {avg_cpu:.2f}%\n平均内存使用率: {avg_mem:.2f}%')
